package cn.wx.autoconfiguration;

import cn.wx.WxOpenConfigStorageFactory;
import cn.wx.WxOpenInMemoryConfigStorageFactory;
import cn.wx.WxOpenServiceRegisterPostProcessor;
import cn.wx.api.WxOpenMultipleService;
import cn.wx.api.impl.WxOpenMultipleServiceImpl;
import cn.wx.common.configuration.WxConfiguration;
import cn.wx.common.properties.WxProperties;
import cn.wx.properties.WxOpenProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;

import static cn.wx.properties.WxOpenProperties.PREFIX;

/**
 * 微信公众平台配置
 *
 * @author: sunshaoping
 * @date: Create by in 5:12 下午 2020/5/23
 */
@Import(WxConfiguration.class)
@EnableConfigurationProperties(WxOpenProperties.class)
@ConditionalOnProperty(prefix = PREFIX, value = "enabled", havingValue = "true", matchIfMissing = true)
public class WxOpenAutoConfiguration {

    private final WxOpenProperties properties;

    public WxOpenAutoConfiguration(WxOpenProperties properties) {
        this.properties = properties;
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean
    public WxOpenMultipleService wxMaMultipleService() {
        properties.verification(PREFIX);
        return new WxOpenMultipleServiceImpl(properties.getName());
    }

    @Bean
    @ConditionalOnMissingBean(name = "wxOpenServiceRegisterPostProcessor")
    public WxOpenServiceRegisterPostProcessor wxOpenServiceRegisterPostProcessor(WxOpenConfigStorageFactory<WxProperties> wxOpenConfigStorageFactory) {
        return new WxOpenServiceRegisterPostProcessor(properties, wxOpenConfigStorageFactory);
    }

    @Bean
    @ConditionalOnMissingBean
    public WxOpenConfigStorageFactory<WxProperties> wxOpenConfigStorageFactory() {
        return new WxOpenInMemoryConfigStorageFactory();
    }

}
